//
//  TIMContactsViewController.m
//  Demo_sdk
//
//  Created by Deli Xia on 2018/6/28.
//  Copyright © 2018年 Deli Xia. All rights reserved.
//

#import "TIMContactsViewController.h"
#import "TIMDemoMacro.h"
#import "TIMFriendCell.h"
#import "TIMNewFriendVC.h"
#import "TIMAddGroupViewController.h"
#import "TIMAddCommonVC.h"
#import "TIMChatMessageViewController.h"

#import "TIMStorageModel.h"
#import "TIMStorageManager.h"

@interface TIMContactsViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableview;
@property (nonatomic, strong) NSMutableArray *friendData;  // 原始数组

@property (nonatomic, strong) UILocalizedIndexedCollation *localizedCollection;
@property (nonatomic, strong) NSMutableArray *sectionHeaders;
@property (nonatomic, strong) NSMutableArray *data;     // 格式化的好友数据（二维数组，列表用）

@end

@implementation TIMContactsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"通讯录";
    self.friendData = [[[TIMStorageManager sharedStorageManager] getAllFriendInfo] mutableCopy];
    [self setupFriendData];
    [self.view addSubview:self.tableview];
  
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateFriend:) name:TIM_OPERATE_FRIEND_ACTION_BROADCAST object:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = NO;
    
    NSInteger unreadcount = [[TIMStorageManager sharedStorageManager] getNewFriendUnreadTotalCount];
    NSLog(@"nureadcount:%d",unreadcount);
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}

- (void)updateFriend:(NSNotification *)noti {
    NSDictionary *userInfo = noti.userInfo;
    switch ([userInfo[@"TIMMessageFriendOperation"] integerValue]) {
        case TIMMsgOperation_OperationFriAdd:
            NSLog(@"好友操作： TIMMsgOperation_OperationFriAdd");
        case TIMMsgOperation_OperationFriConfirm:
            NSLog(@"好友操作： TIMMsgOperation_OperationFriConfirm");
            break;
        default:
            break;
    }
    
    dispatch_async(dispatch_get_main_queue(), ^{
        self.friendData = [[[TIMStorageManager sharedStorageManager] getAllFriendInfo] mutableCopy];
        [self setupFriendData];
        [self.tableview reloadData];
    });
}

#pragma mark - UITableviewDelegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.data.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 3;
    } else {
        NSMutableArray *tempArray = self.data[section];
        return tempArray.count;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return nil;
    }
    id label = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"headerView"];
    if (!label) {
        label = [[UILabel alloc] init];
        [label setFont:TPSFontSize(14.5)];
        [label setTextColor:[UIColor blackColor]];
        [label setBackgroundColor:RGBColor(240, 240, 240)];
    }
    
    [label setText:[NSString stringWithFormat:@"  %@",self.sectionHeaders[section]]];
    
    return label;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIde=@"cellIde";
    TIMFriendCell *cell=[tableView dequeueReusableCellWithIdentifier:cellIde];
    if (cell==nil) {
        cell=[[TIMFriendCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIde];
    }
    
    NSMutableArray *tempArray = self.data[indexPath.section ];
    TIMUserInfo *user = tempArray[indexPath.row];;
    [cell setUser:user];
    [cell fillData:indexPath unRead:0];
    return cell;
}

// 拼音首字母检索
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    return self.sectionHeaders;
}

// 检索时空出搜索框
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
    if(index == 0) {
        [self.tableview scrollRectToVisible:CGRectMake(0, 0, tableView.frame.size.width, tableView.frame.size.height) animated:NO];
        return -1;
    }
    return index;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            TIMNewFriendVC *vc = [TIMNewFriendVC new];
            [self.navigationController pushViewController:vc animated:YES];
        } else if (indexPath.row == 1) {
            TIMAddGroupViewController *vc = [TIMAddGroupViewController new];
            [self.navigationController pushViewController:vc animated:YES];
        } else if (indexPath.row == 2) {
            TIMAddCommonVC *vc = [TIMAddCommonVC new];
            [self.navigationController pushViewController:vc animated:YES];
        }
    } else {
        TIMUserInfo *userInfo = [self.data[indexPath.section] objectAtIndex:indexPath.row];
        TIMChatMessageViewController *vc = [TIMChatMessageViewController new];
        vc.messagePartner = userInfo;
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
    }
}

#pragma mark - SetupData

- (void)setupFriendData {
    // 1、排序
    //初始化UILocalizedIndexedCollation
    self.localizedCollection = [UILocalizedIndexedCollation currentCollation];
    //得出collation索引的数量，这里是27个（26个字母和1个#）
    NSInteger sectionTitlesCount = [[self.localizedCollection sectionTitles] count];
    //初始化一个数组newSectionsArray用来存放最终的数据
    NSMutableArray *newSectionsArray = [[NSMutableArray alloc] initWithCapacity:sectionTitlesCount];
    //初始化27个空数组加入newSectionsArray
    for (NSInteger index = 0; index < sectionTitlesCount; index++) {
        NSMutableArray *array = [[NSMutableArray alloc] init];
        [newSectionsArray addObject:array];
    }
    //将每个人按name分到某个section下
    for (TIMUserInfo *user in self.friendData) {
        //获取name属性的值所在的位置，比如"林丹"，首字母是L，在A~Z中排第11（第一位是0），sectionNumber就为11
        NSInteger sectionNumber = [self.localizedCollection sectionForObject:user collationStringSelector:@selector(showName)];
        NSMutableArray *sectionNames = newSectionsArray[sectionNumber];
        [sectionNames addObject:user];
    }
    //对每个section中的数组按照name属性排序
    for (int index = 0; index < sectionTitlesCount; index++) {
        NSMutableArray *personArrayForSection = newSectionsArray[index];
        NSArray *sortedPersonArrayForSection = [self.localizedCollection sortedArrayFromArray:personArrayForSection collationStringSelector:@selector(showName)];
        newSectionsArray[index] = sortedPersonArrayForSection;
    }
    //section title
    [self.sectionHeaders removeAllObjects];
    NSMutableArray *tempArr = [NSMutableArray array];
    [newSectionsArray enumerateObjectsUsingBlock:^(NSArray *array, NSUInteger idx, BOOL * _Nonnull stop) {
        
        if (array.count == 0) {
            [tempArr addObject:array];
        }else{
            [self.sectionHeaders addObject:[self.localizedCollection sectionTitles][idx]];
        }
    }];
    
    if (self.sectionHeaders.count > 0) {
        [self.sectionHeaders insertObject:UITableViewIndexSearch atIndex:0];
    } else {
        [self.sectionHeaders addObject:UITableViewIndexSearch];
    }
    [newSectionsArray removeObjectsInArray:tempArr];
    
    self.data = [NSMutableArray arrayWithArray:newSectionsArray];
    
    TIMUserInfo *item_new = [[TIMUserInfo alloc] init];
    [item_new setValue:@"-1" forKey:@"userID"];
    [item_new setValue:@"新朋友" forKey:@"remarkName"];
   
    TIMUserInfo *item_new2 = [[TIMUserInfo alloc] init];
    [item_new2 setValue:@"-2" forKey:@"userID"];
    [item_new2 setValue:@"群组" forKey:@"remarkName"];

    TIMUserInfo *item_new3 = [[TIMUserInfo alloc] init];
    [item_new3 setValue:@"-3" forKey:@"userID"];
    [item_new3 setValue:@"评论组" forKey:@"remarkName"];
    
    NSMutableArray *aa = [NSMutableArray array];
    [aa addObject:item_new];
    [aa addObject:item_new2];
    [aa addObject:item_new3];
    if (self.data.count > 0) {
        [self.data insertObject:aa atIndex:0];
    } else {
        [self.data addObject:aa];
    }
}

#pragma mark - Getter

- (NSMutableArray *)sectionHeaders {
    if (!_sectionHeaders) {
        _sectionHeaders = [NSMutableArray new];
    }
    return _sectionHeaders;
}


- (UITableView *)tableview {
    if (!_tableview) {
        _tableview=[[UITableView alloc]initWithFrame:CGRectMake(0.0, 0.0, Screen_Width, Screen_Height-64.0) style:UITableViewStylePlain];
        _tableview.backgroundColor = [UIColor whiteColor];
        [_tableview setDelegate:self];
        [_tableview setDataSource:self];
        [_tableview setSectionIndexBackgroundColor:[UIColor clearColor]];
        [_tableview setSectionIndexColor:[UIColor darkGrayColor]];
//        _tableview.tableHeaderView = self.searchController.searchBar;
        [_tableview setSeparatorInset:UIEdgeInsetsZero];
        //cell无数据时，不显示间隔线
        UIView *v = [[UIView alloc] initWithFrame:CGRectZero];
        [_tableview setTableFooterView:v];
    }
    return _tableview;
}

@end
